<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容"
                    v-model="queryInfo.query"
                    clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"/>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="userlist" border stripe>
        <el-table-column type="index"/>
        <el-table-column prop="username" label="姓名"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="mobile" label="电话"/>
        <el-table-column prop="role_name" label="角色"/>
        <el-table-column prop="mg_state" label="状态" width="80px">
          <!--显示行数据-->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
              <el-button type="primary" icon="el-icon-edit" size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
              <el-button type="danger" icon="el-icon-delete" size="mini"
                         @click="removeUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页插件-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="pageSizes"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--添加用户对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改用户对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
    </el-dialog>
    <!--分配角色对话框-->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="setRolesDialogClosed"
    >
      <div>
        <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <p>
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Users",
    data() {
      return {
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        pageSizes: [5, 10, 20, 50],
        userlist: [],
        total: 0,
        addDialogVisible: false,
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        addFormRules: {
          username: [
            {required: true, message: '请输入用户名称', trigger: 'blur'},
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {
              min: 3,
              max: 15,
              message: '长度在 3 到 15 个字符',
              trigger: 'blur'
            }],
          email: [
            {required: true, message: '邮箱', trigger: 'blur'},
            {validator: this.checkEmail, trigger: 'blur'}],
          mobile: [
            {required: true, message: '手机号', trigger: 'blur'},
            {validator: this.checkMobile, trigger: 'blur'}],
        },
        editDialogVisible: false,
        editForm: {},
        editFormRules: {
          email: [
            {required: true, message: '邮箱', trigger: 'blur'},
            {validator: this.checkEmail, trigger: 'blur'}],
          mobile: [
            {required: true, message: '手机号', trigger: 'blur'},
            {validator: this.checkMobile, trigger: 'blur'}],
        },
        setRolesDialogVisible: false,
        // 需要被分配角色的用户信息
        userInfo: {},
        rolesList: [],
        selectedRoleId: '',
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      getUserList() {
        this.$store.dispatch('getUsersList_', this.queryInfo).then(() => {
          this.userlist = this.$store.state.users_list
          this.total = this.$store.state.users_total
        })
      },
      //监听pagesize改变
      handleSizeChange(newPageSize) {
        this.queryInfo.pagesize = newPageSize
        this.getUserList()
      },
      handleCurrentChange(newPageNum) {
        this.queryInfo.pagenum = newPageNum
        this.getUserList()
      },
      //监听状态改变
      userStateChanged(row) {
        let url = `users/${row.id}/state/${row.mg_state}`
        this.$store.dispatch('updateUserState_', url).then(() => {
          let code = this.$store.state.user_state
          if (code !== 200) {
            row.mg_state = !row.mg_state
            return this.$message.error("更新用户状态失败")
          }
          this.$message.success("更新用户状态成功")
        })
      },
      //自定义邮箱规则
      checkEmail(rule, value, callback) {
        const regEmail = /^\w+@\w+(\.\w+)+$/
        if (regEmail.test(value)) {
          // 合法邮箱
          return callback()
        }
        callback(new Error('请输入合法邮箱'))
      },
      // 自定义手机号规则
      checkMobile(rule, value, callback) {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
          return callback()
        }
        // 返回一个错误提示
        callback(new Error('请输入合法的手机号码'))
      },
      //监听添加关闭
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      //编辑框关闭
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      //添加用户
      addUser() {
        this.$refs.addFormRef.validate(valid => {
          if (!valid) return
          this.$store.dispatch('addUser_', this.addForm).then(() => {
            this.addDialogVisible = false
            this.getUserList()
          })
        })
      },
      //显示编辑歇息
      showEditDialog(id) {
        this.$store.dispatch('getUserById_', id).then(() => {
          if (this.$store.state.user_state !== 200) {
            return this.$message.error("查询用户信息失败")
          }
          this.editForm = this.$store.state.user
        })
        this.editDialogVisible = true
      },
      //编辑更新用户信息
      editUserInfo() {
        this.$refs.editFormRef.validate(valid => {
          if (!valid) return
          let params = {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
          this.$store.dispatch('editUserInfo_', {id: this.editForm.id, user: params}).then(() => {
            if (this.$store.state.user_state !== 200) {
              return this.$message.error("更新用户信息失败")
            }
            this.editDialogVisible = false
            this.getUserList()
            this.$message.success("更新用户信息成功")
          })

        })
      },
      //删除用户
      removeUserById(id) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteUserById_', id).then(() => {
            if (this.$store.state.user_state !== 200) {
              return this.$message.error("删除失败")
            }
            this.getUserList()
            this.$message({type: 'success', message: '删除成功!'});
          })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        })
      },
      ////监听角色对话框关闭后清空
      setRolesDialogClosed() {
        this.selectedRoleId = ''
        this.userInfo = {}
      },
      setRole(role) {
        this.userInfo = role
        this.$store.dispatch('getRolesList_').then(() => {
          if (this.$store.state.roles_state !== 200) {
            return this.$message.error("查询角色列表失败")
          }
          this.rolesList = this.$store.state.roles_list
        })
        this.setRolesDialogVisible = true
      },
      saveRoleInfo() {
        if (!this.selectedRoleId) {
          return this.$message.error("请选择要分配的角色")
        }
        this.$store.dispatch('saveRoleInfo_',
          {id: this.userInfo.id, rid: {rid: this.selectedRoleId}}).then(() => {
          if (this.$store.state.save_state !== 200) {
            return this.$message.error("分配角色失败")
          }
          this.getUserList()
          this.$message.success("角色添加成功")
        })
        this.setRolesDialogVisible = false
      },
    }
  }
</script>

<style lang="less" scoped>

</style>
